package com.jci.vsd.activity.UserInfo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jci.vsd.R;
import com.jci.vsd.activity.BaseActivity;
import com.jci.vsd.activity.RegisterCertActivity;
import com.jci.vsd.application.VsdApplication;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.view.widget.SimpleToast;

import java.text.SimpleDateFormat;
import java.util.List;

import butterknife.BindView;
import cn.unitid.spark.cm.sdk.business.service.CertificateService;
import cn.unitid.spark.cm.sdk.business.service.DeleteCertService;
import cn.unitid.spark.cm.sdk.data.entity.Certificate;
import cn.unitid.spark.cm.sdk.data.response.DataProcessResponse;
import cn.unitid.spark.cm.sdk.exception.CmSdkException;
import cn.unitid.spark.cm.sdk.listener.DataListener;
import cn.unitid.spark.cm.sdk.listener.ProcessListener;

/**
 * Created by liqing on 18/8/20.
 * 查看证书详情
 */

public class CertDetailActivity extends BaseActivity implements DataListener {


    @BindView(R.id.certificate_name)
    TextView tvCerName;

    @BindView(R.id.certificate_time)
    TextView tvCerValidTime;

    @BindView(R.id.certificate_algorithm)
    TextView tvCerAlgorithm;

    @BindView(R.id.certificate_button)
    Button btnExtension;

    @BindView(R.id.btn_delete_cert)
    Button btnDeleteCert;

    //返回键
    @BindView(R.id.button_back)
    ImageButton backBtn;


    private List<Certificate> certificateArrayList;//证书集合
    private String userId;
    private String signCerId; //验签
    private String encCertificateId;///证书

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.certificate_info);
        initData();
        initViewEvent();
    }

    private void initData() {
        // --------提取容器中的证书 start ----------------

        userId = VsdApplication.getUserId();
        CertificateService service = new CertificateService(userId, this);
        service.getCertificateList();
        // --------提取容器中的证书 end ----------------
    }

    @Override
    protected void initViewEvent() {
        btnExtension.setOnClickListener(this);
        btnDeleteCert.setOnClickListener(this);
        backBtn.setOnClickListener(this);

    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.certificate_button) {
            Toast.makeText(CertDetailActivity.this, "待开放", Toast.LENGTH_SHORT).show();
        } else if (view.getId() == R.id.btn_delete_cert) {
            warningDialog("确定删除证书？");
        } else if (view.getId() == R.id.button_back) {
            this.finish();
        }

    }


    @Override
    protected void warningDialog(String message) {
        new AlertDialog.Builder(CertDetailActivity.this)
                .setTitle(getResources().getString(R.string.notice))
                .setMessage(message)
                .setPositiveButton(getResources().getString(R.string.sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //
//                        if (!TextUtils.isEmpty(signCerId) && !TextUtils.isEmpty(encCertificateId)) {
//                            deleteCertificate(signCerId, encCertificateId);
//                        } else {
//                            SimpleToast.toastMessage("证书信息不全，无法删除！", Toast.LENGTH_SHORT);
//                        }

                        deleteCertificate(signCerId, encCertificateId);
                    }
                })
                .setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create().show();
    }

    //加载证书回调
    @Override
    public void onData(List<Certificate> certificates) {

        certificateArrayList = certificates;
        if (certificateArrayList != null && !certificateArrayList.isEmpty()) {
            final Certificate certificate = certificateArrayList.get(0);
            signCerId = certificate.getId();
            encCertificateId = certificate.getEncCertId();
            tvCerName.setText(certificate.getName());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String validate = "有效期至：" + formatter.format(certificate.getNotAfter());
            tvCerValidTime.setText(validate);
            tvCerAlgorithm.setText(certificate.getX509Certificate().getAlgorithm());

            Loger.e("--signCerId" + signCerId);
            Loger.e("--encCertId" + encCertificateId);
//            setText(viewHolder.nameView, certificate.getName());
//            setText(viewHolder.algorithmTV, certificate.getX509Certificate().getAlgorithm());
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//            String validate = "有效期至：" +formatter.format(certificate.getNotAfter());
//            setText(viewHolder.keyUsage, validate);
//          tvCerName.setText();

        }
    }
//
//    // 提取加密证书
//    CertificateService encCertificateService = new CertificateService(userId, new DataListener() {
//        @Override
//        public void onData(List<Certificate> certificates) {
//
//            // 根据id查询的证书有且会只有一条
//            if (certificates != null && !certificates.isEmpty()) {
//                Certificate encCertificate = certificates.get(0);
//                encTitleView.setText(encCertificate.getName());
//                if (encCertificate.getX509Certificate() != null) {
//                    encAlgorithmView.setText(encCertificate.getX509Certificate().getAlgorithm());
//                    encStateView.setText("已签发");
//                    encSNView.setText(encCertificate.getSerialNumber());
//                    encThumbprintView.setText(encCertificate.getFingerPrint());
//                    encThemeView.setText(encCertificate.getSubject());
//                    encIssueView.setText(encCertificate.getIssuer());
//                    if (encCertificate.getNotAfter() != null && encCertificate.getNotBefore() != null) {
//                        encValidityView.setText(format.format(encCertificate.getNotBefore()) + " - " + format.format(encCertificate.getNotAfter()));
//                    }
//                    encKeyUsageView.setText("加密");
//                }
//            }
//        }
//    });

    /**
     * 删除证书
     */
    private void deleteCertificate(String signCerId, String encCertId) {
        //showLoading("正在删除，请稍候...");

        DeleteCertService deleteCertService = new DeleteCertService(this, userId, new
                ProcessListener<DataProcessResponse>() {
                    @Override
                    public void doFinish(DataProcessResponse a, String cert) {

                        SimpleToast.toastMessage("删除成功，请前去申请一张", Toast.LENGTH_SHORT);
                        toActivity(RegisterCertActivity.class);
                        finish();

                    }

                    @Override
                    public void doCancel() {
                        // hideLoading();
                        Log.e("deleteCertificate", "doCancel");
                    }

                    @Override
                    public void doException(CmSdkException exception) {
                        //  hideLoading();
                        Log.e("deleteCertificate", "doException:" + exception.getMessage());
                        // Toast.makeText(CertificateDetailActivity.this, exception.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

//        signCertId = intent.getStringExtra("signCertId");
//        encCertificateId = intent.getStringExtra("encCertId");
        deleteCertService.deleteCertificate(signCerId, encCertId);
    }

}
